var express = require('express');
var router = express.Router();
var {cateModel,wareModel} = require('../models/model')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/cate',async(req,res) => {
  let cate = await cateModel.find()
  res.send({
    code:200,
    data:cate
  })
})

router.get('/ware',async(req,res) => {
  let page = req.query.page
  let pagesize = req.query.pageSize
  console.log(page,pagesize);
  
  let total = await wareModel.find()
  let ware = await wareModel.find().populate('cate').skip((page-1)*pagesize).limit(pagesize)
  res.send({
    code:200,
    data:ware,
    total:total.length
  })
})

router.post('/ware',async(req,res) => {
  await wareModel.create(req.body)
  res.send({
    code:200
  })
})

router.put('/ware',async(req,res) => {
  let id = req.body._id
  await wareModel.updateOne({_id:id},req.body)
  res.send({
    code:200
  })
})

router.delete('/ware',async(req,res) => {
  let id = req.query.id
  console.log(id,'delete');
  await wareModel.deleteOne({_id:id})
  res.send({
    code:200
  })
})

router.get('/look',async(req,res) => {
  let id = req.query.id
  console.log(id,'look');
  
  let ware = await wareModel.find({_id:id})
  res.send({
    code:200,
    data:ware
  })
})

module.exports = router;
